package com.weishenai.Mapper;

import com.weishenai.Builder.BaseRule;
import com.weishenai.Builder.QueryRuleSqlBuilder;
import org.junit.Test;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.weishenai.Utils.ExecSqlUtils.queryInfo;

/**
 * @Auther: weishenai
 * @Date: 2021/09/30/8:47
 * @Description:
 */
public class QueryMapper {
    /**
     * @Description: 数据库查询方法
     * @Param: [baseRule, tableName]
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Author: weishenai
     * @Date: 2021/9/30
     */
    public List<Map<String, Object>> select(BaseRule baseRule, String tableName) {
        List<Map<String, Object>> result = new ArrayList<>();
        QueryRuleSqlBuilder builder = new QueryRuleSqlBuilder(baseRule);
        try {
            result = queryInfo(builder.queryBuilder(tableName), builder.getValues());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @Description: 分页查询
     * @Param: [tableName
     * pageNumber
     * pageSize
     * @return: java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @Author: weishenai
     * @Date: 2021/10/3
     */
    public List<Map<String, Object>> selectByPage(BaseRule baseRule, String tableName, int pageNumber, int pageSize) {
        List<Map<String, Object>> result = new ArrayList<>();
        QueryRuleSqlBuilder builder = new QueryRuleSqlBuilder(baseRule);
        try {
            result = queryInfo(builder.queryBuilder(tableName, pageSize, pageNumber), builder.getValues());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }

    public int getCount(String tableName) {
        Map<String, Object> result = new HashMap<>();
        BaseRule baseRule = BaseRule.getInstance();
        System.out.println(baseRule);
        QueryRuleSqlBuilder queryRuleSqlBuilder = new QueryRuleSqlBuilder(baseRule);
        try {
            result = queryInfo(queryRuleSqlBuilder.queryCountBuilder(tableName)).get(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return Integer.parseInt(String.valueOf(result.get("total")));
    }
}
